package com.yiren.manager.ctrl.cost;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.entity.YrCaregiver;
import com.yiren.entity.YrCaregiverSalaryMonth;
import com.yiren.entity.YrCgSendOrder;
import com.yiren.entity.YrCgissSalary;
import com.yiren.entity.YrCgsosSalaryDay;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.cost.YrCaregiverSalaryMonthForm;
import com.yiren.manager.form.cost.YrCgSalaryDetailForm;
import com.yiren.manager.form.cost.YrCgissSalaryDescForm;
import com.yiren.manager.form.cost.YrCgsosSalaryDescForm;
import com.yiren.manager.form.department.YrCaregiverForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.service.iface.cost.YrCaregiverSalaryMonthService;
import com.yiren.manager.service.iface.cost.YrCgissSalaryService;
import com.yiren.manager.service.iface.cost.YrCgsosSalaryDayService;
import com.yiren.manager.service.iface.department.YrCaregiverService;
import com.yiren.manager.service.iface.department.YrCgSendOrderService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.utils.ObjectUtils;

@Controller
@RequestMapping("caregiverSalaryMonth")
public class YrCaregiverSalaryMonthController extends GenericController<YrCaregiverSalaryMonthForm, YrCaregiverSalaryMonth>{

	@Autowired
	private YrCaregiverSalaryMonthService selfService;
	
	@Autowired
	private YrCaregiverService caregiverService;
	
	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;
	
	@Autowired
	private YrCgSendOrderService cgSendOrderService;
	
	@Autowired
	private YrElderService elderService;
	
	@Autowired
	private YrCgsosSalaryDayService CgsosSalaryDayService;
	
	@Autowired
	private YrCgissSalaryService cgissSalaryService;
	
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrCaregiverSalaryMonthForm> find(Integer year,Integer month,String subjectRoomId) throws Exception{
		HTTPResult<YrCaregiverSalaryMonthForm> result = new HTTPResult<YrCaregiverSalaryMonthForm>();
		String sqlWhere = "year=?1 AND month=?2 AND subject_room_id=?3";
		LinkedHashMap<String, String> sortMap = new LinkedHashMap<>();
		sortMap.put("createTime", "DESC");
		QueryResult<YrCaregiverSalaryMonth> qr = selfService.find(YrCaregiverSalaryMonth.class, sqlWhere, new Object[]{year,month,subjectRoomId},sortMap);
		List<YrCaregiverSalaryMonthForm> formList = new ArrayList<YrCaregiverSalaryMonthForm>();
		for(YrCaregiverSalaryMonth entity : qr.getResultList()){
			formList.add(toForm(entity));
		}
		result.setData(formList);
		
		return result;
	}
	
	@RequestMapping("updateBetch")
	@ResponseBody
	public HTTPResult<YrCaregiverSalaryMonth> updateBetch(String data) throws SwallowException, MyException{
		HTTPResult<YrCaregiverSalaryMonth> result = new HTTPResult<YrCaregiverSalaryMonth>();
		JsonMapperTool tool = new JsonMapperTool(data);
		List<YrCaregiverSalaryMonth> form = tool.mapper("caregiverList", new TypeReference<ArrayList<YrCaregiverSalaryMonth>>() {});
		
		this.selfService.updateBetch(form);
		return result;
	}
	
	/**
	 * 工资发放
	 * @param ids
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("payoff")
	@ResponseBody
	public HTTPResult<YrCaregiverSalaryMonth> payoff(@RequestParam(required = false, value = "ids[]")String[] ids) throws MyException{
		HTTPResult<YrCaregiverSalaryMonth> result = new HTTPResult<YrCaregiverSalaryMonth>();
		
		for(String id : ids){
			YrCaregiverSalaryMonth entity = selfService.findOne(id);
			if(null!=entity){
				entity.setGrantStatus(1);//设置为发放状态
				selfService.save(entity);
			}
		}
		return result;
	}
	
	@RequestMapping("findDetail")
	@ResponseBody
	public HTTPResult<YrCgSalaryDetailForm> findDetail(String id) throws MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		HTTPResult<YrCgSalaryDetailForm> result = new HTTPResult<YrCgSalaryDetailForm>();
		YrCgSalaryDetailForm form = new YrCgSalaryDetailForm();
		
		if(id==null){
			throwExp("参数有误");
		}
		YrCaregiverSalaryMonth caregiverSalaryMonth = selfService.findOne(id);
		if(null == caregiverSalaryMonth){
			throwExp("查询不到该月工资");
		}
		YrCaregiver caregiver = caregiverService.findOne(caregiverSalaryMonth.getCaregiverId());
		if(null==caregiver){
			throwExp("查询不到护理员信息");
		}
		form.setCaregiverForm(ObjectUtils.objectToObject(caregiver,YrCaregiverForm.class));
		
		//获取所有负责长者
		String sqlWhere = "caregiver_id=?1 AND status=0";
		QueryResult<YrCgSendOrder> qr = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere, new Object[]{caregiver.getCaregiverId()});
		
		List<YrElderBeHospitalForm> elderBeHospitalForms = new ArrayList<YrElderBeHospitalForm>();
		for(YrCgSendOrder entity : qr.getResultList()){
			String elderId = entity.getElderId();
			sqlWhere = "elder_id=?1 AND be_status=0";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere, new Object[]{elderId});
			if(qrElderBeHospital.getTotalRecord()>0){
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class);
				YrElder elder = elderService.findOne(elderId);
				if(null!=elder){
					elderBeHospitalForm.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
				elderBeHospitalForms.add(elderBeHospitalForm);
			}
		}
		form.setElderBeHospitalForms(elderBeHospitalForms);
		
		//获取所有派单标准工资
		Integer year =  caregiverSalaryMonth.getYear();
		Integer month = caregiverSalaryMonth.getMonth();
		
		String monthStr = year + "-"+(month>10?month:"0"+month);
		System.out.println(monthStr);
		sqlWhere = "DATE_FORMAT(date,'%Y-%m') = ?1 AND caregiver_id=?2";
		QueryResult<YrCgsosSalaryDay> qrCgsosSalaryDay = CgsosSalaryDayService.find(YrCgsosSalaryDay.class, sqlWhere, new Object[]{monthStr,caregiver.getCaregiverId()});
		System.out.println(qrCgsosSalaryDay.getTotalRecord());
		Map<String,YrCgsosSalaryDescForm> sosMap = new HashMap<String, YrCgsosSalaryDescForm>();
		
		for(YrCgsosSalaryDay cgsosSalaryDay : qrCgsosSalaryDay.getResultList()){
			YrCgsosSalaryDescForm cgsosSalaryDescForm = null;
			if(sosMap.containsKey(cgsosSalaryDay.getSendStandardName())&&sosMap.get(cgsosSalaryDay.getSendStandardName()).getSalary()-cgsosSalaryDay.getSalary()==0){
				cgsosSalaryDescForm = sosMap.get(cgsosSalaryDay.getSendStandardName());
				cgsosSalaryDescForm.setDays(cgsosSalaryDescForm.getDays()+1);
			}else{
				cgsosSalaryDescForm = new YrCgsosSalaryDescForm();
				cgsosSalaryDescForm.setDays(1);
				cgsosSalaryDescForm.setSalary(cgsosSalaryDay.getSalary());
				cgsosSalaryDescForm.setSendStandardName(cgsosSalaryDay.getSendStandardName());
			}
			sosMap.put(cgsosSalaryDay.getSendStandardName(), cgsosSalaryDescForm);
		}
		
		List<YrCgsosSalaryDescForm> cgsosSalaryDescForms = new ArrayList<YrCgsosSalaryDescForm>();
		for(Map.Entry<String, YrCgsosSalaryDescForm> entry : sosMap.entrySet()){
			cgsosSalaryDescForms.add(entry.getValue());
		}
		form.setCgsosSalaryDescForms(cgsosSalaryDescForms);
		
		QueryResult<YrCgissSalary> qrCgissSalary = cgissSalaryService.find(YrCgissSalary.class, sqlWhere, new Object[]{monthStr,caregiver.getCaregiverId()});
		
		Map<String,YrCgissSalaryDescForm> cgissMap = new HashMap<String, YrCgissSalaryDescForm>();
		
		for(YrCgissSalary cgissSalary : qrCgissSalary.getResultList()){
			YrCgissSalaryDescForm cgissSalaryDescForm = null;
			if(cgissMap.containsKey(cgissSalary.getIndiServiceName())&&cgissMap.get(cgissSalary.getIndiServiceName()).getSalary()-cgissSalary.getSalary()==0){
				cgissSalaryDescForm = cgissMap.get(cgissSalary.getIndiServiceName());
				cgissSalaryDescForm.setDays(cgissSalaryDescForm.getDays()+1);
			}else{
				cgissSalaryDescForm = new YrCgissSalaryDescForm();
				cgissSalaryDescForm.setDays(1);
				cgissSalaryDescForm.setSalary(cgissSalary.getSalary());
				cgissSalaryDescForm.setIndiServiceName(cgissSalary.getIndiServiceName());
			}
			cgissMap.put(cgissSalary.getIndiServiceName(), cgissSalaryDescForm);
		}
		
		List<YrCgissSalaryDescForm> cgissSalaryDescForms = new ArrayList<YrCgissSalaryDescForm>();
		for(Map.Entry<String, YrCgissSalaryDescForm> entry : cgissMap.entrySet()){
			cgissSalaryDescForms.add(entry.getValue());
		}
		form.setCgissSalaryDescForms(cgissSalaryDescForms);
		
		List<YrCgSalaryDetailForm> formList = new ArrayList<YrCgSalaryDetailForm>();
		formList.add(form);
		result.setData(formList);
		
		return result;
	}
	@Override
	public YrCaregiverSalaryMonthForm toForm(YrCaregiverSalaryMonth e) throws Exception {
		YrCaregiverSalaryMonthForm form = ObjectUtils.objectToObject(e, YrCaregiverSalaryMonthForm.class);
		return form;
	}

	@Override
	public YrCaregiverSalaryMonth toEntity(YrCaregiverSalaryMonthForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
